package com.jah.picavue.client.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.jah.picavue.client.EventBus;
import com.jah.picavue.client.Config;
import com.jah.picavue.client.events.GotAlbumDataEvent;
import com.jah.picavue.client.events.GotAlbumFeedEvent;
import com.jah.picavue.client.events.GotUserFeedEvent;
import com.jah.picavue.client.events.GotUserDataEvent;

@SuppressWarnings("unchecked")
public class User implements Config, GotUserFeedEvent.Handler, GotAlbumFeedEvent.Handler {

	private String username;
	private ArrayList<Album> albums;
	private HashMap<String, Album> albumsMap = new HashMap();
	private String activeAlbumID = null;
	private Iterator<Album> albumIter;
	public final static User INSTANCE = new User();

	private User() {
		EventBus.get().addHandler(GotUserFeedEvent.TYPE, this);
		EventBus.get().addHandler(GotAlbumFeedEvent.TYPE, this);
	}

	public void setUsername(String name) {
		this.username = name;
	}
	
	public String getUsername() {
		return this.username;
	}
	
	public void setActiveAlbum(String id) {
		activeAlbumID = id;
	}
	public String getActiveAlbum() {
		return activeAlbumID;
	}

	public void addAlbum(Album album) {
		albumsMap.put(album.getID(), album);
	}
	public void deleteAlbum(String id) {
		albumsMap.remove(id);
	}
	public void clearAlbums() {
		albumsMap.clear();
	}
	public Album getAlbum(String id) {
		if (albumsMap.containsKey(id)) {
			activeAlbumID = id;
		}
		return albumsMap.get(id);
	}

	public int getAlbumsCount() {
		return albumsMap.size();
	}

	public boolean isAlbum(String id) {
		return albumsMap.containsKey(id);
	}

	public Album getNextAlbum() {
		if (albumIter == null || !albumIter.hasNext()) albumIter = albums.iterator();
		Album a = (Album) albumIter.next();
		return a;
	}

	public void onGotUserFeed(GotUserFeedEvent event) {
		JSONObject json = event.getFeed();
		JSONArray entries = json.get("feed").isObject().get("entry").isArray();
		clearAlbums();
		for (int i = 0; i < entries.size(); ++i) {
			addAlbum(new Album(entries.get(i)));
		}
		albums = new ArrayList(albumsMap.values());
		EventBus.get().fireEvent(new GotUserDataEvent());
	}

	public void onGotAlbumFeed(GotAlbumFeedEvent event) {
		JSONObject json = event.getFeed();
		String id = json.get("feed").isObject().get("gphoto$id").isObject().get("$t").isString().stringValue();
		albumsMap.get(id).addPhotos(json.get("feed").isObject().get("entry").isArray());
		GotAlbumDataEvent evt = new GotAlbumDataEvent();
		evt.setData(albumsMap.get(id));
		EventBus.get().fireEvent(evt);
	}
}
